package com.iweipan.activity;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.iweipan.MyApplication;
import com.iweipan.R;
import com.iweipan.base.WPBaseActivity;
import com.iweipan.base.WPUrlBase;
import com.iweipan.utils.snackbar.SnackbarUtil;
import com.iweipan.utils.sputils.SPUtils;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.tencent.android.tpush.XGPushConfig;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

import static com.iweipan.base.WPUrlBase.WP_BIND_RE;
import static com.iweipan.base.WPUrlBase.WP_IS_REGSISTER;
import static com.iweipan.base.WPUrlBase.WP_LOGIN_RE;

/**
 * Created by Administrator on 2016/11/11.
 */

public class LoginActivity extends WPBaseActivity {


    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.text)
    TextView text;
    @BindView(R.id.materialedittext)
    MaterialEditText materialedittext;
    @BindView(R.id.password_materialedittext)
    MaterialEditText password_materialedittext;
    @BindView(R.id.register)
    Button register;
    @BindView(R.id.login)
    Button login;

    @Override
    public int bindLayout() {
        return R.layout.activity_login;
    }

    @Override
    public void initToolbarColor() {
        color = getResources().getColor(R.color.actionbar_title_bg);
        statusBarAlpha = 60;
    }


    @Override
    public void initView(View view) {

        initTitle();
    }


    /**
     * 设置toolbar与标题
     */
    private void initTitle() {
        toolbar.setTitle("");
        toolbar.setNavigationIcon(R.drawable.back_title);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//        Typeface typeFace = Typeface.createFromAsset(getAssets(), "fonts/Roboto-LightItalic.ttf");
//        text.setTypeface(typeFace);
    }

    @Override
    public void doBusiness(Context mContext) {
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        if (getIntent().getStringExtra("from") != null) {
            if (getIntent().getStringExtra("from").equals("RegisterActivity")) {
                String mobile = getIntent().getStringExtra("mobile");
                String password = getIntent().getStringExtra("password");
                materialedittext.setText(mobile);
                password_materialedittext.setText(password);
            }
        }


    }

    @Override
    public void resume() {

    }

    @Override
    public void destroy() {

    }


    @OnClick({R.id.register, R.id.login})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.register:
                Intent intent = new Intent(getContext(), RegisterActivity.class);
                startActivity(intent);
                finish();
                break;
            case R.id.login:

                LoginInit();
                break;
        }
    }

    private void LoginInit() {
        MyApplication.getImm().hideSoftInputFromWindow(materialedittext.getWindowToken(), 0);
        if (materialedittext.length() != 11) {
            SnackbarUtil.shortMake(materialedittext, "请输入11位手机号码").show();
            return;
        }
        if (password_materialedittext.length() < 6) {
            SnackbarUtil.shortMake(materialedittext, "请输入6位及以上密码").show();
            return;
        }
        final String mobile = materialedittext.getText().toString();
        OkHttpUtils.get()
                .url(WPUrlBase.LOGIN)
                .addParams("mobile", mobile)
                .addParams("password", password_materialedittext.getText().toString())
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
//                        Log.e("LoginActivity", e.toString());

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("LoginActivity", response);
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            int ret = jsonObject.getInt("ret");
                            String info = jsonObject.getString("info");
                            if (ret == 0) {
                                SPUtils.put(LoginActivity.this, "isLogin", true);
                                SPUtils.put(LoginActivity.this, "mobile", mobile);
                                SnackbarUtil.shortMake(password_materialedittext, "登录成功").show();
                                initIsRegister();
                                SPUtils.put(LoginActivity.this, "user_icon", jsonObject.getString("portrait"));
                                SPUtils.put(LoginActivity.this, "user_name", jsonObject.getString("userName"));

                                getMessageForServer(jsonObject.getString("userId"));
                            } else {
                                SnackbarUtil.shortMake(password_materialedittext, info).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });


    }

    /**
     * 获取软件版本号
     */
    private int getAPPVersion() {
        PackageManager pm = this.getPackageManager();//得到PackageManager对象

        try {
            PackageInfo pi = pm.getPackageInfo(this.getPackageName(), 0);//得到PackageInfo对象，封装了一些软件包的信息在里面
            int appVersion = pi.versionCode;//获取清单文件中versionCode节点的值
//            Log.d(TAG, "appVersion="+appVersion);
            return appVersion;
//            setVersion(getString(R.string.app_version)+":"+String.valueOf(appVersion));
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
//            Log.e(TAG, "getAppVersion:"+e.getCause());
        }
        return 1;
    }


    private void getMessageForServer(String userId) {
        Log.e("LoginActivity", userId);
//        PrefHelper.get().put("deviceToken", XGPushConfig.getToken(context));
//        Log.e("LoginActivity", XGPushConfig.getToken(this));

        SPUtils.put(this, "userId", userId);

        OkHttpUtils
                .post()
                .addParams("deviceToken", XGPushConfig.getToken(this))
                .addParams("appVersion", getAPPVersion() + "")
                .addParams("deviceId", "1")
                .addParams("appVersion", "1")
                .addParams("appId", "yanhao")
                .addParams("os", "ANDROID")
                .addParams("userId", userId)
                .url(WP_LOGIN_RE)
//                .addParams("userType", PrefHelper.get().getInt("userType", 0) + "")
                .build()
                .execute(new SaveMessage(userId));
//        Log.i("userType", PrefHelper.get().getInt("userType", 0) + "");
//        Log.i("TPushReceiver", PrefHelper.get().getString("userId", "") + "");
    }

    private class SaveMessage extends StringCallback {
        private String userId;

        public SaveMessage(String userId) {
            this.userId = userId;
        }

        @Override
        public void onError(Call call, Exception e, int id) {
            e.printStackTrace();

        }

        @Override
        public void onResponse(String response, int id) {
//            Log.e("SaveMessage", response);

            try {
                JSONObject jsonObject = new JSONObject(response);
                String ret = jsonObject.getString("ret");
                if (ret.equals("1")) {
                    OkHttpUtils.get()
                            .url(WP_BIND_RE)
                            .addParams("userId",userId)
                            .build()
                            .execute(new StringCallback() {
                                @Override
                                public void onError(Call call, Exception e, int id) {
                                    e.printStackTrace();
                                }

                                @Override
                                public void onResponse(String response, int id) {
                                    Log.e("SaveMessage", response);
                                }
                            });
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }

    private void initIsRegister() {

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("mobile", materialedittext.getText().toString());
            jsonObject.put("mid", "016");
            OkHttpUtils.get()
                    .url(WP_IS_REGSISTER)
                    .addParams("p", jsonObject.toString())
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            Log.e("LoginActivity", e.toString());
                        }

                        @Override
                        public void onResponse(String response, int id) {
                            try {
//                                Log.d("LoginActivity", response);
                                JSONObject request = new JSONObject(response);
                                if (request.get("code").equals("200")) {

                                    Intent intent = new Intent(LoginActivity.this, WebViewActivity.class);
                                    intent.putExtra("mobile", materialedittext.getText().toString());
                                    startActivity(intent);
                                    finish();

                                } else if (request.get("code").equals("1030")) {
                                    Intent intent = new Intent(LoginActivity.this, WebViewActivity.class);
                                    intent.putExtra("mobile", materialedittext.getText().toString());
                                    startActivity(intent);
                                    finish();
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
}
